package com.xintong.visualinspection.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xintong.system.err.BusinessException;
import com.xintong.system.securityTools.RedisCacheUtil;
import com.xintong.visualinspection.bean.User;
import com.xintong.visualinspection.service.AuthService;
import com.xintong.visualinspection.service.UserService;

/**
 * 文件名：TestController
 * 版本信息：日期：2017/3/30 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 */
/**
 * @author wenhongquan
 *
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    
    @Value("${jwt.header}")
    private String tokenHeader;

    @RequestMapping(value = "/auth/login",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String login(@RequestBody User user){
    	User u = authService.login(user.getUsername(), user.getPassword());
        return returnSuccessResult("登陆成功", u);
    }
    
   
    
    @RequestMapping(value = "/logout",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String logout(){
    	//获取用户名
    	String username = SecurityContextHolder.getContext().getAuthentication().getName();
    	if(username!=null){
    		redisCacheUtil.removeForUserName(username);
    	}
    	//返回成功
    	return returnSuccessResult("退出成功");
    }
    
    
    
    
    
    /**
     * 添加用户
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/addUser",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String addUser(@RequestBody User user) throws Exception{
    	user.setPassword(new Md5PasswordEncoder().encodePassword(user.getPassword(), null));
    	userService.insert(user);
    	return returnResult(0, "添加成功", null);
    }
    
    /**
     * 修改用户
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/updateUser/{userid}",method=RequestMethod.PUT,produces="application/json;charset=UTF-8")
    public String updateUser(@RequestBody User user,@PathVariable int userid){
        try{
        	user.setId(userid);
        	userService.update(user);
        	return super.returnResult(0, "修改成功", null);
        }catch(Exception e){
        	throw new BusinessException(20003);
        }
    }
    
    /**
     * 删除用户（软删除）
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/deleteUser/{userid}",method=RequestMethod.DELETE,produces="application/json;charset=UTF-8")
    public String deleteUser(@PathVariable Integer userid){
        try{
        	userService.delete((userid));
        	return returnResult(0, "删除成功", null);
        }catch(Exception e){
        	throw new BusinessException(20002);
        }
    }
    
    /**
     * 获取所用用户
     * @param page
     * @param size
     * @return
     */
    @SuppressWarnings("unchecked")
	@PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/get/all/{page}/{size}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getallUsers(@PathVariable Integer page,@PathVariable Integer size ){
        try{
        	PageHelper.startPage(page, size); 
        	List<User> users= userService.getAll();
        	
        	return returnResult(0, "获取成功", new PageInfo(users));
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/getUserList/{page}/{size}",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String getUsers(@PathVariable Integer page,@PathVariable Integer size,@RequestBody User user){
        try{
        	PageHelper.startPage(page, size); 
        	List<User> users= userService.getUsers(user);
        	
        	return returnResult(0, "获取成功", new PageInfo(users));
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    @RequestMapping(value = "/getUserById/{userid}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getUser(@PathVariable Integer userid){
        try{
            User u = userService.getOne(userid);
        	return returnResult(0, "获取成功", u);
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    
    


    
    
    
}
